<script setup>
import {ref, defineExpose} from "vue";
import {getProductList} from "@/api/product";
import {formatAmount} from "@/utils/format";
import {ElMessage} from "element-plus";

const dialogVisible = ref(false)

const emits = defineEmits(['getProduct'])

// 打开
const open = () => {
 dialogVisible.value = true
 getList()
}

// 关闭
const handleClose = () => {
 dialogVisible.value = false
}

const list = ref([])

// 获取商品列表
const loadProduct = ref(false)
const getList = () => {
 loadProduct.value = true
 Promise.try(() => {
  return getProductList()
 }).then(res => {
  res.data.forEach(item => {
   item.latest_price = formatAmount(item.latest_price)
  })
  list.value = res.data
  console.log(list.value)
 })
 loadProduct.value = false
}

const selectionList = ref([])
const handleSelectionChange = (selection) => {
 selectionList.value = selection.map(item => {
  return item.product_code
 })
}

const doConfirm = () => {
 if (!selectionList.value.length) return ElMessage.error('请至少勾选一项')

 // 保存勾选的商品代号
 handleClose()
 emits('getProduct', selectionList.value)
}

// 暴露给父级的方法
defineExpose({
 open
})
</script>

<template>
 <el-dialog
  v-model="dialogVisible"
  title="商品列表"
  width="500"
  :close-on-press-escape="false"
  :close-on-click-modal="false"
  :before-close="handleClose"
 >
  <el-table
   :data="list"
   class="com_table_box"
   @selection-change="handleSelectionChange"
  >
   <el-table-column type="selection"></el-table-column>
   <el-table-column prop="product_name" label="商品代号名称"></el-table-column>
  </el-table>
  <template #footer>
   <div class="dialog-footer">
    <el-button @click="handleClose">取消</el-button>
    <el-button type="primary" @click="doConfirm">
     确认
    </el-button>
   </div>
  </template>
 </el-dialog>
</template>

<style scoped lang="scss">

</style>